package com.climber.android.commonsdk.api

import android.util.Log
import com.google.gson.JsonSyntaxException
import io.ganguo.library.klog.KLog
import io.ganguo.library.mvp.util.ToastHelper
import io.reactivex.Observer
import io.reactivex.disposables.Disposable


/**
 * Created by mikes on 2017-3-24.
 */

abstract class ApiObserver<T> : Observer<T> {
    companion object{
        var DEBUG_MODE = true
    }

    override fun onSubscribe(d: Disposable) {
        //do nothing
    }

    override fun onNext(apiResponse: T) {
        success(apiResponse)
    }

    override fun onError(throwable: Throwable) {
        KLog.e("ApiObserver", "throwable is $throwable , cause by ${Log.getStackTraceString(throwable)}")

        when (throwable) {
            is APIError -> dealError(throwable)
            else -> {
                if(throwable is JsonSyntaxException
                    && DEBUG_MODE){
                    ToastHelper.toastMessage(throwable.localizedMessage)
                    KLog.e("ApiObserver", throwable.localizedMessage)
                }
                dealError(APIError.NormalAPIException(message = throwable.message, cause = throwable.cause))
            }
        }
    }

    /**
     * Tips: if response body is null, this fun will be invoked.
     * see {@link com.ifund.android.util.calladapter.BodyObservable}
     */
    override fun onComplete() {
        completeObserver()
    }

    abstract fun success(apiResponse: T)

    open fun dealError(apiError: APIError) {
    }

    open fun completeObserver() {}
}
